import {BrowserWindow, WebContents, screen} from "electron";
import path from "path";
import {is} from "@electron-toolkit/utils";

export default class RegionFrame {
  #window: BrowserWindow = null
  #webContents: WebContents = null

  constructor() {
    screen.getPrimaryDisplay()
    const {width, height} = screen.getPrimaryDisplay().size

    this.#window = new BrowserWindow({
      title: 'Region',
      width: width,
      maxWidth: width,
      minWidth: 600,
      height: height,
      maxHeight: height,
      minHeight: 300,
      frame: false,
      show: false,
      alwaysOnTop: false,
      backgroundColor: '#00000000',
      resizable: true,
      transparent: true,
      autoHideMenuBar: true,
      ...(process.platform === 'linux'
        ? {
          icon: path.join(__dirname, '../../build/icon.png')
        }
        : {}),
      webPreferences: {
        preload: path.join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    })

    this.#window.on('ready-to-show', () => {
      this.#webContents = this.#window.webContents
      const bounds = this.#window.getBounds()
      this.invoke(bounds)
    })

    // 窗口重置大小
    this.#window.on('resized', () => {
      const bounds = this.#window.getBounds()
      this.invoke(bounds)
    })

    this.#window.on('moved', () => {
      const bounds = this.#window.getBounds()
      this.invoke(bounds)
    })

    this.#window.on('closed', () => {
      this.#window = null
      this.#webContents = null
    })

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      // this.#window.webContents.openDevTools()
      this.#window.loadURL(process.env['ELECTRON_RENDERER_URL'] + "/#/region")
    } else {
      this.#window.loadFile(path.join(__dirname, '../renderer/index.html'), {
        hash: '/region'
      })
    }
  }

  invoke(data){
    this.#webContents.send('main-to-renderer', {
      name: 'window-resized',
      event: 'event',
      data: data
    })
  }

  getWindow(){
    return this.#window
  }

  getWebContents(){
    return this.#webContents
  }

  show(){
    this.#window.show()
  }
}
